import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:cloud_phone_manager/dialog/AdbConnectDialog.dart';
import 'package:cloud_phone_manager/dialog/AppManagerDialog.dart';
import 'package:cloud_phone_manager/provider/AdbCurrentChangeProvider.dart';
import 'package:cloud_phone_manager/provider/AdbDevicesProvider.dart';
import 'package:cloud_phone_manager/utils/CmdUtils.dart';
import 'package:cloud_phone_manager/widget/ContentFragmentView.dart';
import 'package:flutter/material.dart';
import 'package:flutter_styled_toast/flutter_styled_toast.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';

import 'widget/DevicesListView.dart';

void main() {
  CmdUtils.rootAdb();
  runApp(
    ChangeNotifierProvider(
      create: (context) => AdbDevicesProvider(),
      child: const MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  AdbDevicesProvider? _provider;
  List<AdbDeviceInfo> _info = [];
  bool isConnect = false;
  bool _mounted = false;
  bool _isInit = false;

  @override
  void dispose() {
    _mounted = false;
    super.dispose();
  }

  void showConnectDialog() {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AdbConnectDialog(
              title: "ADB",
              onClosed: () => {Navigator.pop(context)},
              onConfirm: (ip) => {
                    if (ip.isNotEmpty)
                      {
                        if (!isConnect)
                          {
                            isConnect = true,
          Navigator.of(context).pop(),
                            CmdUtils.connectAdb(ip,
                                (success, error, process, suListener) {
                              isConnect = false;
                              if (success.isNotEmpty &&
                                  !success.contains("cannot")) {
                                showToast("连接${ip}成功", context: context);
                              } else {
                                showToast("连接失败${success}", context: context);
                              }
                            }),
                          }
                        else
                          {showToast("连接中", context: context)}
                      }
                    else
                      {showToast("请输入连接IP", context: context)}
                  });
        });
  }

  @override
  void initState() {
    super.initState();
    _mounted = true;
    if (!_isInit) {
      _isInit = true;
      startQuery();
    }
  }

  Future<void> startQuery() async {
    // 开启一个定时器，每秒执行一次回调
    Timer.periodic(Duration(seconds: 2), (Timer timer) {
      CmdUtils.devicesAdbList((success, error, process, suListener) => {
            if (success.isNotEmpty && success != "DONE")
              {
                _info.clear(),
                for (String item in success.split("\r\n"))
                  {
                    // debugPrint(item),
                    if (item.isNotEmpty && !item.endsWith("attached"))
                      {
                        _info.add(AdbDeviceInfo(
                            item.split("	")[0], item.split("	")[1] == "device"))
                      }
                  },
                if (_mounted) {_provider?.updateData(_info)}
              }
          });
    });
  }

  @override
  Widget build(BuildContext context) {
    _provider ??= Provider.of<AdbDevicesProvider>(context);
    return ChangeNotifierProvider(
        create: (context) => AdbCurrentChangeProvider(),
        child: Scaffold(
          appBar: null,
          body: Center(
            child: Row(
              children: [
                Expanded(
                  flex: 3,
                  child: Container(
                    color: Colors.white70,
                    width: MediaQuery.of(context).size.width,
                    height: MediaQuery.of(context).size.height,
                    padding: const EdgeInsets.all(8),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text(
                          "设备列表",
                          style: TextStyle(fontWeight: FontWeight.bold),
                        ),
                        Expanded(child: DevicesListView())
                      ],
                    ),
                  ),
                ),
                Container(color: Color.fromARGB(15, 0, 0, 0),height: MediaQuery.of(context).size.height,width: 1,),
                Expanded(
                    flex: 17,
                    child: ContentFragmentView()
                ),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: showConnectDialog,
            tooltip: 'Increment',
            child: const Icon(Icons.add),
          ), // This trailing comma makes auto-formatting nicer for build methods.
        ));
  }
}
